package com.dinero.pagecontents.net

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit

abstract class INetApi {

    private val DEFAULT_TIMEOUT = 15

    private val DEFAULT_SMALL_TIMEOUT = 15

    private val mRetrofits: MutableMap<String, Retrofit> = HashMap<String, Retrofit>()


    abstract fun getBaseUrl(): String
    fun <T> getRetrofit(netApi: Class<T>): Retrofit {
        if (mRetrofits[getBaseUrl().toString() + netApi.name] != null) {
            return mRetrofits[getBaseUrl() + netApi.name]!!
        }
        val retrofit: Retrofit = retrofit2.Retrofit.Builder()
            .client(getOkHttpClient())
            .baseUrl(getBaseUrl())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        mRetrofits[getBaseUrl() + netApi.name] = retrofit

        return retrofit
    }

    private fun getOkHttpClient(): OkHttpClient? {
        val sslParams: HttpsUtils.SSLParams = HttpsUtils.getSslSocketFactory() //Https请求认证
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
            .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
            .connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_SMALL_TIMEOUT.toLong(), TimeUnit.SECONDS)
        if (true) {
            val httpLoggingInterceptor = HttpLoggingInterceptor()
            httpLoggingInterceptor.level = okhttp3.logging.HttpLoggingInterceptor.Level.BODY
            builder.addNetworkInterceptor(httpLoggingInterceptor)
        }

        var interceptors = getInterceptor()
        interceptors?.let {
            for (interceptor in interceptors) {
                builder.addInterceptor(interceptor)
            }
        }
        return builder.build()
    }


    abstract fun getInterceptor(): ArrayList<okhttp3.Interceptor>?
}